﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace SuperKit
{
    class CollectDirName : CommandExecutor {

        private List<string> names;
        private StringBuilder sb;

        public CollectDirName(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath) {
            names = new List<string>();
            sb = new StringBuilder();
        }

        public override void Execute() {
            base.Execute();
            DirectoryInfo info = new DirectoryInfo(FilePath);
            var dirs = info.GetDirectories();
            if (Kit.IsEmpty(dirs)) {
                return;
            }

            foreach (var i in dirs) {
                Collect(i);
            }

        }

        private void Collect(DirectoryInfo dir) {
            names.Clear();
            var dirs = dir.GetDirectories();
            foreach (var i in dirs) {
                var splits = i.Name.Split(' ');
                foreach (var n in splits){
                    StackName(n);
                }
            }
            Flush("{0}:{1}", dir.Name, CollectName());
        }
        private enum NameType {
            Name,
            Alphabet,
            Number
        }
        private string CollectName() {
            sb.Clear();
            CollectName(NameType.Name);
            CollectName(NameType.Alphabet);
            CollectName(NameType.Number);
            return sb.ToString();
        }

        private bool IsMatch(string name, string pattern) {
            var matchs = Regex.Match(name, pattern);
            return matchs.Success;
        }

        private NameType GetType(string name) {
            var number = @"\d";
            var alphabet = @"\w";

            if (IsMatch(name, number)) {
                return NameType.Number;
            }else if (IsMatch(name, alphabet)) {
                return NameType.Alphabet;
            } else {
                return NameType.Name;
            }
        }

        private void CollectName(NameType type) {            

            foreach (var i in names) {
                if (type != GetType(i)) {
                    continue;
                }
                if (sb.Length > 0) {
                    sb.Append("+");
                }
                sb.Append(i);
            }
        }

        private bool IsNameExist(string name) {
            foreach (var i in names) {
                if (Kit.IsEqual(i, name)) {
                    return true;
                }
            }
            return false;
        }


        private void StackName(string name) {
            if (IsNameExist(name)) {
                return;
            }
            names.Add(name);
        }
    }
}
